package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getRequestURI();

        if(token.contains("login")){
            log.info("用户登录: {} " , token);
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = request.getHeader("token");

        if(jwt == null || jwt.isEmpty()){
            log.info("用户未登录: {} " , token);
            response.setStatus(401);
            return;
        }

        try{
            Claims claims = JwtUtils.parseToken(jwt);
            Integer userId = claims.get("id", Integer.class);
            log.info("当前用户存入ID在ThreadLocal");
            CurrentUserHoler.setCurrentUser(userId);
        }catch (Exception e){
            log.info("令牌解析失败: {} " , token);
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(request, response);
        log.info("当前用户从ThreadLocal移除");
        CurrentUserHoler.removeCurrentUser();
    }
}
